package com.yt.ds.chapter4;

import com.yt.ds.chapter1.Bag;
import com.yt.ds.io.In;

/**
 * @Author: lzf
 * @Date: 2020/8/3 14:52
 * @Description: 加权无向图
 */
public class EdgeWeightedGraph implements WeightedGraph<Edge> {
    /**
     * 顶点数
     */
    private final int vertexNum;
    /**
     * 边数
     */
    private int edgeNum;

    private Bag<Edge>[] adj;

    public EdgeWeightedGraph(In in) {
        this(in.readInt());
        int e = in.readInt();
        for (int i = 0; i < e; i++) {
            int v = in.readInt();
            int w = in.readInt();
            double weight = in.readDouble();
            addEdge(new Edge(v, w, weight));
        }
    }

    public EdgeWeightedGraph(int v) {
        this.vertexNum = v;
        this.edgeNum = 0;
        adj = (Bag<Edge>[]) new Bag[v];
        for (int i = 0; i < v; i++) {
            adj[i] = new Bag<>();
        }
    }

    @Override
    public int getVertexNum() {
        return vertexNum;
    }

    @Override
    public int getEdgeNum() {
        return edgeNum;
    }

    @Override
    public void addEdge(Edge edge) {
        int v = edge.either();
        int w = edge.other(v);
        adj[v].add(edge);
        adj[w].add(edge);
        edgeNum++;
    }

    @Override
    public Iterable<Edge> adj(int v) {
        return adj[v];
    }

    @Override
    public Iterable<Edge> edges() {
        Bag<Edge> bag = new Bag<>();
        for (int v = 0; v < vertexNum; v++) {
            for (Edge e : adj[v]) {
                if (e.other(v) > v) {
                    bag.add(e);
                }
            }
        }
        return bag;
    }
}
